package com.virtualmall.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import com.virtualmall.bean.Order;
import com.virtualmall.common.Page;
import com.virtualmall.dao.OrderDao;

@Repository
public class OrderDaoImpl extends GenericDaoHibernateImpl<Order, Long> implements OrderDao {
	public OrderDaoImpl() {
		super(Order.class);
	}

	@SuppressWarnings("unchecked")
	public List<Order> getOrderList(Long userId,String orderType,Page page) {
		String condition = "";
		if(userId != null)
			condition = "where s.account.id = ?";
		
		String hql = "select s.id as id,s.count as count,s.product as product,s.payType as payType," +
				"s.status as status,s.createDate as createDate,s.account as account " +
				"from Order s "+condition+" order by s.createDate "+orderType;
		
        Query query = this.getCurrentSession().createQuery(hql)
                .setResultTransformer(Transformers.aliasToBean(Order.class));
        if(userId != null)
        	query.setLong(0, userId);

        if (page != null) {
            query.setFirstResult((page.getCurrentPage() - 1)
                    * page.getPerPageSize());
            query.setMaxResults(page.getPerPageSize());
        }
        
		return (List<Order>)query.list();
	}

	public Long getOrderListCount(Long userId) {
		String condition = "";
		if(userId != null)
			condition = "where s.account.id = ?";
		
		String hql = "select count(s.id) from Order s "+condition+"";
		
		Query query = this.getCurrentSession().createQuery(hql);
        if(userId != null)
        	query.setLong(0, userId);
		
		return (Long)query.uniqueResult();
	}
}
